var model = {
	validate: function(request, sender, callback) {
		console.log('showing dialog to validate flickr links');
		
		var selected = document.activeElement;
		var text = selected.value;
		var re = /farm\d\.static\.flickr\.com\/\d{3,4}\/(\d{9,10})_(\w{10})(_[smlb])?\.jpg/gi;
		
		if (text.match(re)) {
			var links = [];
			var index = 0;
			var table = dom.create('table').append([
				dom.create('tr').append([
					dom.create('th').html('Image'),
					dom.create('th').html('Valid?').addClass('checkbox')
				])
			]);
			var panel = dom.create('div', { cssClass: 'panel' }).append(table);
			var updateButton = dom.createButton('update-button', 'Save Corrections', function(e) {
				for (var i = 0; i < links.length; i++) {
					text = links[0].update(text);
				}
				selected.value = text;
				dialog.close();
			}).disable();
			
			var dialog = dom.createDialog('flickr-validate','Validate Flickr Links');
		
			dialog
				.status('connected as ' + request.user)
				.append([panel, updateButton])
				.positionBy(selected, 10);
			
			while ((match = re.exec(text)) != null) {
				var link = new linkObject(match[1], match[2]);
				links.push(link);
				table.append(dom.create('tr').append([ link.nameTD, link.validTD ]));
			}
			
			function checkLink() {
				if (index < links.length) {
					links[index++].validate(checkLink);
				} else {
					dialog.hideProgress();
					for (var i = 0; i < links.length; i++) {
						if (!links[i].verified) { updateButton.enable(); }
					}
				}
			}
			checkLink();
			
		} else {
			alert('No Flickr image links were found');
			alert(text);
		}
	},
	insert: function(request, sender, callback) {
		console.log('showing dialog to insert Flickr images');

		var selected = document.activeElement;
		var setList = dom.createList('set-list').disable();
		var sizeList = dom.createList('size-list', {
			'Small Square': 's',
			'Thumbnail': 't',
			'Small': 'm',
			'Medium 500': '-',
			'Medium 640': 'z',
			'Large': 'b',
			'Original': 'o'
		}).setSelected('b');
		
		var dialog = dom.createDialog('flickr-insert','Insert Flickr Set');
		
		var insertButton = dom.createButton('insert-button', 'Insert', function(e) {
			insertButton.disable();
			dialog.showProgress();
			
			chrome.extension.sendRequest(
				{'action': 'getSet', 'id': setList.selected().value },
				function(r) {
					selected.innerHTML = JSON.stringify(r);
					dialog.close();
				}
			);
		}).disable();

		dialog
			.status('connected as ' + request.user)
			.appendChildren([setList, insertButton, sizeList])
			.positionBy(selected, 10);
		
		chrome.extension.sendRequest(
			{'action': 'getSets', 'id': null },
			function(r) {
				setList.enable();
				for (var i = 0; i < r.json.length; i++) {
					setList.append(
						r.json[i].title + ' [' + r.json[i].total + ']',
						r.json[i].id
					);
				}
				insertButton.enable();
				dialog.hideProgress();
			}
		);
	},
	options: function(request, sender, callback) {
		callback(sender.id);
	}
};

chrome.extension.onRequest.addListener(
	function(request, sender, callback) { model[request.method](request, sender, callback); }
);

function linkObject(id, secret) {
	var _this = this;
	var _photo = null;
	var _secret = null;
	var _oldSecret = secret;
	var _checkbox = dom.create('input', {'type': 'checkbox'}).disable();
	
	this.id = id;
	this.verified = false;
	this.nameTD = dom.create('td').html(id);
	this.validTD = dom.create('td').append(_checkbox);
	this.validate = function(callback) {
		var css = 'working';
		_this.nameTD.addClass(css);
		_this.validTD.addClass(css);
		chrome.extension.sendRequest({'action': 'getPhoto', 'id': _this.id },
			function(p) {
				_secret = p.secret;
				_this.nameTD.removeClass(css);
				_this.validTD.removeClass(css);
				if (_secret == _oldSecret) {
					_this.verified = true;
					_checkbox.check();
					_this.nameTD.html(p.title);
				} else {
					_this.nameTD.addClass('invalid');
				}
				if (callback) { callback(); }
			}
		);
	}
	this.update = function(text) {
		return text.replace(
			_this.id + '_' + _oldSecret,
			_this.id + '_' + _secret
		);
	}
}